package com.zx.mes.hyl.auth.dao;

import com.zx.mes.hyl.auth.model.Tuser;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author hyl
 * @date 2017-12-6
 */
public interface UserRepository extends JpaRepository<Tuser,String>,JpaSpecificationExecutor<Tuser> {

    /**
     * 根据用户名获得角色
     * @param username
     * @return tuser
     */
    Tuser findByUsername(String username);

    List<Tuser> findByUsername(String username, Pageable pageable);

    Tuser findByUsernameAndPassword(String username, String password);

    @Query("select distinct t from Tuser t left join fetch t.troles role where t.id = :id")
    Tuser getByUserId(@Param("id") String id);


    @Query("select distinct t from Tuser t left join fetch t.troles role where t.username = :userName")
    Tuser getByUserName(@Param("userName") String userName);

    @Query("select t from Tuser t join fetch t.troles role join fetch role.tresources resource join fetch resource.tresourcetype tresourcetype where t.id = :id")
    Tuser getResourceByUserId(@Param("id") String id);

    @Query("select t from Tuser t join fetch t.troles role join fetch role.tresources resource where t.id = :id")
    Tuser getMenuByUserId(@Param("id") String id);

    @Transactional
    @Modifying
    @Query("update Tuser u set u.username = ?1,u.password=?2,u.modifydatetime=?3 where u.id = ?4")
    int updateById(String username, String password, Date modifydatetime, String id);

    Tuser findById(String id);
}
